<template>
  <div id="intfconfig">
    <Splitpanes style="height: 100%">
      <Pane size="100">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" status="info" :icon="sourcelist.length > 0?'vxe-icon-success-circle':'vxe-icon-download'" content="载入外源参数" @click="getsource"></vxe-button>
            <vxe-button type="text" status="info" icon="vxe-icon-download" content="载入标准参数" @click="getstandard"></vxe-button>
            <vxe-button type="text" status="primary" icon="vxe-icon-refresh" content="刷新" @click="handleSearch"></vxe-button>
            <vxe-button type="text" status="success" icon="vxe-icon-square-plus" content="新建" @click="handleAdd"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-save" content="保存" class="text-cyan" @click="saveList"></vxe-button>
            <vxe-button type="text" status="danger" icon="vxe-icon-delete" content="删除" @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="modulTable">
          <vxe-table ref="moduleTable" v-loading="loading" :loading="loading" :height="conHeight - 150 + 'px'" border :data="intfItemSettingsList" @current-change="moduleRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" @cell-dblclick="editRow" :edit-rules="formRule" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="26" align="center"></vxe-column>
            <vxe-column type="seq" title="序号" width="30" align="center"></vxe-column>
            <vxe-column field="outsource" title="外源参数" min-width="120" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-select v-model="row.outsource" clearable filterable v-if="sourcelist.length > 0">
                  <vxe-option :value="item" :label="item" v-for="item in sourcelist" :key="item"></vxe-option>
                </vxe-select>
                <vxe-input v-model="row.outsource" type="text" @keydown.enter="enterEvent(row, rowIndex, column)" v-else></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="standard" title="标准参数" min-width="120px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.standard" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="paramnotes" title="参数说明" min-width="120px" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.paramnotes" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="ishave" width="90" title="是否必传">
              <template #default="{ row }">
                <vxe-switch v-model="row.ishave" size="mini" open-icon="vxe-icon-check" close-icon="vxe-icon-close" open-value="0" close-value="1"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="where" width="90" title="条件参数">
              <template #default="{ row }">
                <vxe-switch v-model="row.where" size="mini" open-icon="vxe-icon-check" close-icon="vxe-icon-close" open-value="0" close-value="1"></vxe-switch>
              </template>
            </vxe-column>
            <vxe-column field="sn" title="顺序" width="50" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row, rowIndex, column }">
                <vxe-input v-model="row.sn" type="text" @keydown.enter="enterEvent(row, rowIndex, column)"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Splitpanes, Pane } from 'splitpanes';
import { ElMessage } from 'element-plus';
// import { fa } from 'element-plus/es/locale';
import { VXETable } from 'vxe-table';
import { VxeMessage } from '../../../utils/CommonMessage';
import { AppStore } from '../../../stores/store';
//import saveAs from 'file-saver';
import { defineProps } from 'vue';
let props = defineProps<{
  itemform: any;
}>();
let store = AppStore();
let { proxy }: any = getCurrentInstance();
let modulePoitPre = reactive([]);
// 当前屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);
let leftpane = ref('100');
let rightpane = ref('0');
//关键字
let keywords = ref('');
let loading = ref(false);
// 接口表格数据
let intfItemSettingsList = reactive([]);
let maindialogVisible = ref(false);
let mainform = reactive({
  id: '',
  code: '', //编码
  name: '', //名称
  intfId: '', //所属模块
  type: '', //类型
  state: 0, //状态
  sn: 0, //排序号
  //数据库
  source: '', //外源表
  standard: '', //标准表
  template: '', //校准模板
  settings: '' //配置细项
});

onMounted(() => {
  handleSearch();
});

// 点击刷新
function handleSearch() {
  loading.value = true;
  let intfParam = reactive({
    id: props.itemform.id
  });
  intfItemSettingsList.length = 0; //放入数据前清空数组
  proxy.$http.post('/api/sys/getIntfItem', intfParam).then((res: any) => {
    if (res.status.code === 1) {
      const data = res.data;

      setvalue(mainform, data);
      if (mainform.settings) {
        const records = JSON.parse(mainform.settings);
        intfItemSettingsList.push(...records);
      }
      loading.value = false;
    } else {
      VXETable.modal.message({ content: res.status.msg, status: 'error' });
      return;
    }
  });
}
//新建
async function handleAdd() {
  const record = {
    outsource: '',
    standard: '',
    paramnotes: '',
    ishave: '1',
    where: '1',
    sn: intfItemSettingsList.length + 1
  };
  intfItemSettingsList.push(record);
}
async function saveRow() {
  if (!mainform.id) {
    mainform.id = '2000' + mainform.sn;
    intfItemSettingsList.push(mainform);
  } else {
    for (let i = intfItemSettingsList.length - 1; i >= 0; i--) {
      if (mainform.id == intfItemSettingsList[i].id) {
        setvalue(intfItemSettingsList[i], mainform);
        break;
      }
    }
  }
  localStorage.setItem('intfItemSettingList', JSON.stringify(intfItemSettingsList));
  VXETable.modal.message({ content: '操作成功', status: 'success' });
  maindialogVisible.value = false;
  setTimeout(() => {
    handleSearch();
  }, 500);
}
async function editRow({ row }) {
  clearmainform();
  setvalue(mainform, row);
  maindialogVisible.value = true;
}
function setvalue(form, row) {
  form.id = row.id;
  (form.code = row.code), //编码
    (form.name = row.name), //名称
    (form.intfId = row.intfId), //所属模块
    (form.type = row.type), //类型
    (form.state = row.state), //状态 禁用/调试/启用
    (form.sn = row.sn), //排序号
    //数据库
    (form.source = row.source), //数据库地址
    (form.standard = row.standard); //数据库名称
  form.template = row.template; //校准模板
  form.settings = row.settings; //配置细项
}
function clearmainform() {
  mainform.id = '';
  (mainform.code = ''), //编码
    (mainform.name = ''), //名称
    (mainform.intfId = ''), //所属模块
    (mainform.type = ''), //类型
    (mainform.state = 0), //状态 禁用/调试/启用
    (mainform.sn = 0), //排序号
    //数据库
    (mainform.source = ''), //外源表
    (mainform.standard = ''); //标准表
  mainform.template = ''; //校准模板
  mainform.settings = ''; //配置细项
}
// 点击修改保存
async function saveList() {
  loading.value = true;
  const data = {
    id: props.itemform.id,
    settings: JSON.stringify(intfItemSettingsList)
  }
  proxy.$http
    .post('/api/sys/saveIntfItemSettings', data)
    .then((res: any) => {
      if (res.status.code === 1) {
        handleSearch();
        maindialogVisible.value = false;
        VXETable.modal.message({ content: '修改成功', status: 'success' });
      }
    })
    .catch((err: any) => {
      VXETable.modal.message({ content: '修改异常', status: 'error' });
    });
  setTimeout(() => {
    handleSearch();
    loading.value = false;
  }, 500);
}
// 点击删除
async function handleDelete() {
  let $Xtable = proxy.$refs.moduleTable;
  let selectRows = $Xtable.getCheckboxRecords();
  if (selectRows <= 0) {
    VXETable.modal.message({ content: `请勾选要删除的数据`, status: 'warning' });
    return;
  }
  const type = await VXETable.modal.confirm('您确定要删除吗？');
  if (type != 'cancel') {
    for (const item of selectRows) {
      for (let i = intfItemSettingsList.length - 1; i >= 0; i--) {
        if (item.code == intfItemSettingsList[i].code) {
          intfItemSettingsList.splice(i, 1);
          break;
        }
      }
    }
    saveList();
  }
}
// 点击行
function moduleRowClick({ row, rowIndex }) {
  leftpane.value = '25';
  rightpane.value = '75';
}

// 载入外源参数模拟数据
let sourcelist: any = reactive([]);
function getsource() {
  const data = {
    id: props.itemform.id,
  }
  sourcelist.length = 0;
  proxy.$http
    .post('/api/sys/getSource', data)
    .then((res: any) => {
      if (res.status.code === 1) {
        sourcelist.push(...res.data);
        VXETable.modal.message({ content: '加载成功', status: 'success' });
      } else {
        VXETable.modal.message({ content: '加载异常', status: 'error' });
      }
    })
    .catch((err: any) => {
      VXETable.modal.message({ content: '获取异常', status: 'error' });
    });
}
// 载入标准参数模拟数据
function getstandard() {
  findDictAndDetailList();
}
function findDictAndDetailList() {
  intfItemSettingsList.length = 0;
  const url = '/api/sys/basDict/findDictAndDetailList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pid: mainform.standard } })
    .then((res: any) => {
      const detailListTemp = res.data.detailList.sort((a, b) => a.sx - b.sx);
      for (const detail of detailListTemp) {
        if (detail.type == '模板') continue;
        intfItemSettingsList.push({
          outsource: '',
          standard: detail.code,
          paramnotes: detail.name,
          ishave: detail.ishave ? detail.ishave : '1',
          where: detail.where ? detail.where : '1',
          sn: detail.sx
        })
      }
    });
}
</script>
<style lang="scss" scoped>
#intfconfig {
  .el-form-item {
    margin-right: 10px;
  }
  .el-tabs {
    margin-left: 10px;
  }
  .el-select {
    width: 100%;
  }
  .el-input-number {
    width: 100%;
  }
}
</style>
